package com.rico.kok.service;

import com.rico.kok.mapper.UserMapper;
import com.rico.kok.entity.User;
import com.rico.kok.service.interf.UserService;
import com.rico.kok.tool.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@EnableTransactionManagement(proxyTargetClass = true)
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> selectUsers(User user) {
        return userMapper.selectUsers(user);
    }

    public int insertUser(User user) {
        String password = user.getUserPassword();
        String salt = SaltUtils.getSalt(8);
        password = new Md5Hash(password, salt, 789).toHex();
        user.setUserPassword(password);
        user.setSalt(salt);
        return userMapper.insertUser(user);
    }

    //通过更新指定的字段以提高数据库的写入效率
    public int updateUser(User user) {
        int re = 0;
        if (user.getUserEmail() != null) {
            re += userMapper.updateUserEmail(user);
        }
        if (user.getUserName() != null) {
            re += userMapper.updateUserName(user);
        }
        if (user.getUserPassword() != null) {
            String password = user.getUserPassword();
            String salt = SaltUtils.getSalt(8);
            password = new Md5Hash(password, salt, 789).toHex();
            user.setUserPassword(password);
            user.setSalt(salt);
            re += userMapper.updateUserPassword(user);
        }
        if (user.getUserImage() != null) {
            re += userMapper.updateUserImage(user);
        }
        if (user.getUserGender() != null) {
            re += userMapper.updateUserGender(user);
        }
        if (user.getUserBirthday() != null) {
            re += userMapper.updateUserBirthday(user);
        }
        if (user.getUserDetail() != null) {
            re += userMapper.updateUserDetail(user);
        }
        return re;
    }

    public int deleteUser(User user) {
        return userMapper.deleteUser(user);
    }

    public boolean verifyEmail(String email) {
        User user = new User();
        user.setUserEmail(email);
        List<User> users = userMapper.selectUsers(user);
        if (users.size() == 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<User> selectUsersByIds(List<Integer> ids) {
        return userMapper.selectUsersByIds(ids);
    }
}
